package com.example.bankend.service.method;



import com.example.bankend.mapper.CardMapper;
import com.example.bankend.mapper.TransactionMapper;
import com.example.bankend.model.BankCard;
import com.example.bankend.model.Transaction;
import com.example.bankend.model.TransferDto;
import com.example.bankend.service.impl.TransactionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Timestamp;
import java.util.List;

@Service
public class TransactionServiceImpl implements TransactionService {
    @Autowired
    private TransactionMapper transactionMapper;
    @Autowired
    private CardMapper bankCardMapper;

    @Override
    public int insert(Transaction transaction) {
        return transactionMapper.insert(transaction);
    }

    @Override
    public int deleteByPrimaryKey(Integer tradeID) {
        return transactionMapper.deleteByPrimaryKey(tradeID);
    }

    @Override
    public int updateByPrimaryKey(Transaction transaction) {
        return transactionMapper.updateByPrimaryKey(transaction);
    }

    @Override
    public Transaction selectByPrimaryKey(Integer tradeID) {
        return transactionMapper.selectByPrimaryKey(tradeID);
    }
    @Override
    public List<Transaction> selectByCardID(String cardID) {
        return transactionMapper.selectByCardID(cardID);
    }
    //转账处理
    @Override
    @Transactional
    public String transfer(TransferDto transferDto) {
        try {
            // 验证转出卡状态
            BankCard card1 = bankCardMapper.selectByPrimaryKey(transferDto.getCardId1());
            if (card1 == null) {
                return "转出卡不存在";
            }
            if ("是".equals(card1.getIsReportLoss())) {
                return "转出卡正在挂失状态，您无权操作";
            }

            // 验证转入卡状态
            BankCard card2 = bankCardMapper.selectByPrimaryKey(transferDto.getCardId2());
            if (card2 == null) {
                return "转入卡不存在";
            }
            if ("是".equals(card2.getIsReportLoss())) {
                return "转入卡正在挂失状态，您无权操作";
            }

            // 调用存储过程进行转账
            transactionMapper.transferByProcedure(transferDto);
            return "转账成功";
        } catch (Exception e) {
            // 捕获存储过程抛出的异常
            if (e.getMessage().contains("转出卡不存在")) {
                return "转出卡不存在";
            } else if (e.getMessage().contains("转入卡不存在")) {
                return "转入卡不存在";
            } else if (e.getMessage().contains("余额不足")) {
                return "余额不足";
            } else {
                // 其他异常
                e.printStackTrace();
                return "转账失败: " + e.getMessage();
            }
        }
    }
    @Override
    public List<Transaction> selectAll() {
        return transactionMapper.selectAll();
    }
}
